package com.zzf.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzf.eduservice.entity.EduSubject;
import com.zzf.eduservice.entity.excel.SubjectData;
import com.zzf.eduservice.entity.subject.OneSubject;
import com.zzf.eduservice.entity.subject.TwoSubject;
import com.zzf.eduservice.listener.SubjectExcelListener;
import com.zzf.eduservice.mapper.EduSubjectMapper;
import com.zzf.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-04-05
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分裂
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {

        try {
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取所有课程分类数据
    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //1:查询所有的一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);


        //2:查询所有的二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);

        //3:封装数据
        //创建list集合,用于存储最终数据
        ArrayList<OneSubject> finalSubjectList = new ArrayList<>();

        for (EduSubject eduSubject : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);

            //创建一个集合封装每个一级分类的二级分类
            ArrayList<TwoSubject> twoFinalSubjectList = new ArrayList<>();
            for (EduSubject twoSubject : twoSubjectList) {
                if (twoSubject.getParentId().equals(oneSubject.getId())){
                    TwoSubject newTwoSubject = new TwoSubject();
                    BeanUtils.copyProperties(twoSubject,newTwoSubject);
                    twoFinalSubjectList.add(newTwoSubject);
                }
            }
            oneSubject.setChildren(twoFinalSubjectList);
            finalSubjectList.add(oneSubject);
        }

        return finalSubjectList;
    }
}
